import 'package:contract_manager/components/components.dart';
import 'package:contract_manager/pages/contract_list/contract_list_controller.dart';
import 'package:contract_manager/router/app_pages.dart';
import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

class ContractListPage extends GetView<ContractListController> {
  const ContractListPage({super.key});

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      appBar: MyAppBar(
        centerTitle: true,
        title: MyTitle('合同列表'),
        leadingType: AppBarBackType.None,
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }

        if (controller.contracts.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.assignment_outlined,
                  size: 64,
                  color: Colors.grey[300],
                ),
                const SizedBox(height: 16),
                Text(
                  '暂无合同数据',
                  style: TextStyle(
                    fontSize: 18,
                    color: Colors.grey[500],
                  ),
                ),
              ],
            ),
          );
        }

        return Padding(
          padding: const EdgeInsets.all(16),
          child: Obx(
            () => DataTable2(
              columnSpacing: 12,
              horizontalMargin: 12,
              minWidth: 600,
              columns: const [
                DataColumn(label: Text('合同编号')),
                DataColumn(label: Text('客户名称')),
                DataColumn(label: Text('项目名称')),
                DataColumn(label: Text('签订日期')),
                DataColumn(label: Text('到期日期')),
                DataColumn(label: Text('状态')),
                DataColumn(label: Text('操作')),
              ],
              rows: controller.contracts.map((contract) {
                final dateFormat = DateFormat('yyyy-MM-dd');
                final status = _getContractStatus(contract.expirationDate);
                final statusColor =
                    status.contains('已到期') ? Colors.red : Colors.green;

                return DataRow(
                  cells: [
                    DataCell(Text(contract.contractNumber)),
                    DataCell(Text(contract.customerName)),
                    DataCell(Text(contract.projectName)),
                    DataCell(Text(dateFormat.format(contract.contractDate))),
                    DataCell(Text(dateFormat.format(contract.expirationDate))),
                    DataCell(
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 8,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: statusColor.withOpacity(0.2),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          status,
                          style: TextStyle(
                            color: statusColor,
                            fontSize: 12,
                          ),
                        ),
                      ),
                    ),
                    DataCell(
                      Row(
                        children: [
                          IconButton(
                            icon: const Icon(Icons.remove_red_eye),
                            onPressed: () async {
                              /*Get.dialog(
                                AlertDialog(
                                  title: Text('合同详情'),
                                  content: SingleChildScrollView(
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                            '合同编号: ${contract.contractNumber}'),
                                        SizedBox(height: 8),
                                        Text('客户名称: ${contract.customerName}'),
                                        SizedBox(height: 8),
                                        Text('项目名称: ${contract.projectName}'),
                                        SizedBox(height: 8),
                                        Text(
                                            '签订日期: ${DateFormat('yyyy-MM-dd').format(contract.contractDate)}'),
                                        SizedBox(height: 8),
                                        Text(
                                            '到期日期: ${DateFormat('yyyy-MM-dd').format(contract.expirationDate)}'),
                                      ],
                                    ),
                                  ),
                                  actions: [
                                    TextButton(
                                      onPressed: () => Get.back(),
                                      child: Text('关闭'),
                                    ),
                                  ],
                                ),
                              );*/
                              Get.toNamed(
                                AppRoutes.ContractDetail,
                                arguments: {"id": contract.id},
                              );
                            },
                          ),
                          IconButton(
                            icon: const Icon(Icons.delete),
                            onPressed: () async {
                              await Get.dialog(
                                AlertDialog(
                                  title: const Text('确认删除'),
                                  content: const Text('确定要删除该合同吗？此操作不可恢复。'),
                                  actions: [
                                    TextButton(
                                      onPressed: () => Get.back(),
                                      child: const Text('取消'),
                                    ),
                                    TextButton(
                                      onPressed: () => controller
                                          .deleteContract(contract.id),
                                      child: const Text('删除',
                                          style: TextStyle(color: Colors.red)),
                                    ),
                                  ],
                                ),
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  ],
                );
              }).toList(),
            ),
          ),
        );
      }),
    );
  }

  String _getContractStatus(DateTime expirationDate) {
    final now = DateTime.now();
    if (now.isAfter(expirationDate)) {
      return '已到期';
    }
    final diff = expirationDate.difference(now).inDays;
    return '剩余${diff}天';
  }
}
